package xushuo.web.controller.weixin;

import org.springframework.beans.factory.annotation.Autowired;
import xushuo.dao.entity.weixin.managementUser.JsonToObject;
import xushuo.dao.entity.weixin.user.PublicUserInfo;
import xushuo.dao.service.tools.format.ChangeFormat;
import xushuo.dao.service.tools.password.SHA1;
import org.apache.log4j.Logger;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import xushuo.dao.service.tools.weixin.WeiXinUtil;
import xushuo.dao.service.userinfo.PublicUserInfoService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Create by zhangpe0312@qq.com on 2018/1/31.
 */

@Controller
public class tokenController {

    private static Logger logger = Logger.getLogger(tokenController.class);

    @Autowired
    WeiXinUtil weiXinUtil;
    @Autowired
    JsonToObject jsonToObject;
    @Autowired
    PublicUserInfoService publicUserInfoService;

    /**
     * 验证这个服务器是否为管理员的服务器
     *
     * @param rq
     * @param rsp
     */
    @RequestMapping(value = "/token", method = {RequestMethod.GET})
    public void getToken(HttpServletRequest rq, HttpServletResponse rsp) {

        String signature = rq.getParameter("signature");
        String timestamp = rq.getParameter("timestamp");
        String nonce = rq.getParameter("nonce");
        String echostr = rq.getParameter("echostr");

        logger.info(" signature : " + signature);

        if (checkToken(signature, timestamp, nonce)) {
            logger.info("验证成功");
            try {
                rsp.getWriter().write(echostr);
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("返回字符串错误" + e);
            }
        }

        logger.info("验证失败");
    }

    /**
     * 微信核心工作区
     * 接收来自于微信客户端的信息
     *
     * @param rq
     * @param rsp
     * @return 向微信服务器返回响应信息
     */
    @RequestMapping(value = "/token", method = {RequestMethod.POST})
    @ResponseBody
    public void CenterWork(HttpServletRequest rq, HttpServletResponse rsp) {

        logger.info("进入post");
        Map<String, String> map;
        try {
            map = ChangeFormat.messageToMap(rq);
            logger.info("用户： " + map.get("FromUserName"));
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e);
        } catch (DocumentException e) {
            e.printStackTrace();
            logger.error(e);
        }
    }


    /**
     * 通过用户的Openid获取到用户的信息
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/getUserInfoByOpenID", method = {RequestMethod.GET})
    @ResponseBody
    public Map<String, String> getUserInfoByOpenID(HttpServletRequest req) {

        Map<String, String> map = new HashMap<>();
        if (req.getParameter("openid") != "" && req.getParameter("openid") != "") {
            try {
                PublicUserInfo info = (PublicUserInfo) jsonToObject
                        .jsonToObject(req.getParameter("openid"));
                publicUserInfoService.save(info);
                logger.info("获取PublicUserInfo信息成功");
                map.put("msg", "ok");
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("获取PublicUserInfo信息失败" + e);
                map.put("msg", "erro");
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("从微信添加用户信息失败 " + e);
            }
        }
        return map;
    }

    private boolean checkToken(String signature, String timestamp, String nonce) {

        String Token = "xushuo";

        List<String> params = new ArrayList<String>();
        params.add(Token);
        params.add(timestamp);
        params.add(nonce);
        //1. 将token、timestamp、nonce三个参数进行字典序排序
        Collections.sort(params, new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        //2. 将三个参数字符串拼接成一个字符串进行sha1加密
        String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));

        if (temp.equals(signature)) {
            logger.info("返回数据");
            return true;
        } else {
            logger.info("没有返回数据");
            return false;
        }
    }
}
